//
//  ViewController.m
//  TSMSGHookDemo
//
//  Created by YYInc on 2020/3/4.
//  Copyright © 2020 caoxuerui. All rights reserved.
//

#import "ViewController.h"
#import "TSHookMSG.h"
#include <objc/runtime.h>
#import <Dobby/dobby.h>


@interface ViewController ()

@end

@implementation ViewController

+ (void)load {
    
    NSLog(@"load");
}

//+ (void)load {
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
//        SEL fromSelectorAppear = @selector(viewWillAppear:);
//        SEL toSelectorAppear = @selector(clsCallHookViewWillAppear:);
//        [ViewController hookClass:self fromSelector:fromSelectorAppear toSelector:toSelectorAppear];
//
//        SEL fromSelectorDisappear = @selector(viewWillDisappear:);
//        SEL toSelectorDisappear = @selector(clsCallHookViewWillDisappear:);
//
//        [ViewController hookClass:self fromSelector:fromSelectorDisappear toSelector:toSelectorDisappear];
//    });
//}

//函数指针用于保留原来的执行流程
static int(*sum_p)(int a,int b);

int sum(int a,int b){
    return  a + b;
}

//新函数
int mySum(int a,int b){
    NSLog(@"原有的结果是:%d",sum_p(a,b));
    return a - b;
}

//+(void)load
//{
//    //Hook sum
//    DobbyHook(sum, mySum, (void *)&sum_p);
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(50, 100, 100, 100);
    button.backgroundColor = [UIColor blueColor];
    [button addTarget:self action:@selector(buttonCilck) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    [button setTitle:@"开始" forState:UIControlStateNormal];
    
    
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
    button1.frame = CGRectMake(150, 100, 100, 100);
    button1.backgroundColor = [UIColor redColor];
    [button1 addTarget:self action:@selector(buttonCilck1) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button1];
    [button1 setTitle:@"结束" forState:UIControlStateNormal];
    
    
    UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
    button2.frame = CGRectMake(100, 300, 100, 100);
    button2.backgroundColor = [UIColor greenColor];
    [button2 addTarget:self action:@selector(buttonCilck2) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button2];
    [button2 setTitle:@"测试" forState:UIControlStateNormal];
    

    
}

- (void)buttonCilck {
//    DobbyDestroy(&sum);
//    DobbyDestroy(&mySum);
//    DobbyDestroy(&sum_p);
    
//    NSLog(@"打印出：%d",sum(10, 20));
//    [self.navigationController pushViewController:[ViewController new] animated:YES];
    
    smCallTraceStart();
}

- (void)buttonCilck1 {
    smCallTraceStop();
}

- (void)buttonCilck2{
    UIView *view = [[UIView alloc] init];
    NSLog(@"测试");
    [self test];
   
}

- (void)test {
    
    dispatch_queue_t dd = dispatch_queue_create("com.test", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(dd, ^{
        NSLog(@"dddd");
        
    });
}

+ (void)startWithMaxDepth:(int)depth {
    smCallConfigMaxDepth(depth);
    [ViewController startFunction];
}

+ (void)startFunction {
    smCallTraceStart();
}

+ (void)save {
//    NSMutableString *mStr = [NSMutableString new];
//    NSArray<SMCallTraceTimeCostModel *> *arr = [self loadRecords];
//    for (SMCallTraceTimeCostModel *model in arr) {
//        //记录方法路径
//        model.path = [NSString stringWithFormat:@"[%@ %@]",model.className,model.methodName];
//        [self appendRecord:model to:mStr];
//    }
    
//    NSLog(@"time：%@",mStr);
    [self loadRecords];
}

+ (void)loadRecords {
//    NSMutableArray<SMCallTraceTimeCostModel *> *arr = [NSMutableArray new];
    NSString *className;
    NSString *methodName;
    BOOL isClassMethod;
    NSTimeInterval timeCost;
    NSUInteger callDepth;
    NSString *path;
    BOOL lastCall;
    NSUInteger frequency;
    int num = 0;
    smCallRecord *records = smGetCallRecords(&num);
    for (int i = 0; i < num; i++) {
        smCallRecord *rd = &records[i];
//        SMCallTraceTimeCostModel *model = [SMCallTraceTimeCostModel new];
        className = NSStringFromClass(rd->cls);
        methodName = NSStringFromSelector(rd->sel);
        isClassMethod = class_isMetaClass(rd->cls);
        timeCost = (double)rd->time / 1000000.0;
        callDepth = rd->depth;
//        [arr addObject:model];
        NSLog(@"className:%@,methodName:%@,timeCost:%f",className,methodName,timeCost);
    }
//    NSUInteger count = arr.count;
//    for (NSUInteger i = 0; i < count; i++) {
//        SMCallTraceTimeCostModel *model = arr[i];
//        if (model.callDepth > 0) {
//            [arr removeObjectAtIndex:i];
//            //Todo:不需要循环，直接设置下一个，然后判断好边界就行
//            for (NSUInteger j = i; j < count - 1; j++) {
//                //下一个深度小的话就开始将后面的递归的往 sub array 里添加
//                if (arr[j].callDepth + 1 == model.callDepth) {
//                    NSMutableArray *sub = (NSMutableArray *)arr[j].subCosts;
//                    if (!sub) {
//                        sub = [NSMutableArray new];
//                        arr[j].subCosts = sub;
//                    }
//                    [sub insertObject:model atIndex:0];
//                }
//            }
//            i--;
//            count--;
//        }
//    }
//    return arr;
}


@end
